<template>
  <div class="clientType">
    <div class="title-container">
      <div class="left-box">
        <el-form ref="form" :model="searchForm" class="formClass">
          <el-form-item>
            <el-input
              prefix-icon="el-icon-search"
              type="input"
              placeholder="请输入客户名称"
              v-model="searchForm.searchInput"
            />
          </el-form-item>
          <el-form-item>
            <el-select
              v-model="searchForm.searchSelectValue"
              placeholder="请选择项目类型"
            >
              <el-option
                v-for="item in customerTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchClick">搜索</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <global-card>
      <template #leftTitle>
        <el-button type="primary" icon="el-icon-plus" @click="newCustomer"
        >添加客户
        </el-button
        >
        <el-button type="success" icon="el-icon-refresh" @click="refresh"
        >刷新
        </el-button
        >
      </template>
      <template #content>
        <el-table
          v-loading="loading"
          :data="tableData"
          border
          style="width: 100%"
          class="elTable"
          ref="tableRef"
        >
          <el-table-column
            type="index"
            label="序号"
            width="80"
            align="center"
          />
          <el-table-column
            prop="customerName"
            label="客户名称"
            align="center"
          />
          <el-table-column
            prop="customerPhone"
            label="客户联系方式"
            align="center"
          />

          <el-table-column
            prop="customerType"
            label="客户类型"
            align="center"
          />
          <el-table-column
            prop="dockingPerson"
            label="对接人员姓名"
            align="center"
          />
          <el-table-column
            prop="dockingPhone"
            label="对接人联系方式"
            align="center"
          />

          <el-table-column label="服务IP" align="center" prop="customerUrl"/>

          <el-table-column label="创建时间" align="center" prop="createTime">
            <template slot-scope="scope">
              {{ scope.row.createTime }}
            </template>
          </el-table-column>

          <el-table-column label="操作" width="250px" align="center">
            <template #default="{ row }">
              <el-button type="warning" size="mini" @click="handlerEdit(row)"
              >编辑
              </el-button>
              <el-button
                type="primary"
                size="mini"
                @click="handlerProject(row)"
              >
                项目
              </el-button>

              <el-button type="danger" size="mini" @click="handlerDelete(row)">
                删除
              </el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </template>
      <template #footer>
        <pagination
          class="pagination"
          :total="count"
          :page.sync="pageIndex"
          :limit.sync="pageSize"
          @pagination="pagination"
        />
      </template>
    </global-card>

    <yc-dialog
      ref="ycDialog"
      :dialogTitle="dialogTitle"
      :centerTitle="dialogCenterTitle"
    >
      <template #content>
        <div class="dialog-content">
          <el-form
            ref="loginFormRef"
            :rules="rules"
            :model="newCustomerModel"
            label-width="120px"
          >
            <el-form-item label="客户名称" prop="customerName">
              <el-input
                v-model="newCustomerModel.customerName"
                :disabled="detailsDisabled"
              />
            </el-form-item>
            <el-form-item label="客户联系方式" prop="customerPhone">
              <el-input
                type="number"
                v-model="newCustomerModel.customerPhone"
                :disabled="detailsDisabled"
              />
            </el-form-item>
            <el-form-item label="客户类型" prop="customerType">
              <el-select
                v-model="newCustomerModel.customerType"
                placeholder="选择客户类型"
                :disabled="detailsDisabled"
              >
                <el-option
                  v-for="item in customerTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="对接人员名称" prop="dockingPerson">
              <el-input
                v-model="newCustomerModel.dockingPerson"
                :disabled="detailsDisabled"
              />
            </el-form-item>
            <el-form-item label="对接人联系方式" prop="dockingPhone">
              <el-input
                type="number"
                v-model="newCustomerModel.dockingPhone"
                :disabled="detailsDisabled"
              />
            </el-form-item>
            <el-form-item label="服务IP" prop="customerUrl">
              <el-input
                v-model="newCustomerModel.customerUrl"
                :disabled="detailsDisabled"
              />
            </el-form-item>
            <el-form-item label="客户logo" prop="customerLogo">
              <el-upload
                :action="$uploadUrl + upload"
                class="avatar-uploader"
                :headers="headers"
                :show-file-list="false"
                :on-success="handleLogoSuccess1"
                :before-upload="beforeAvatarUpload"
              >
                <img
                  v-if="newCustomerModel.customerLogo"
                  :src="newCustomerModel.customerLogo"
                  class="avatar"
                />
                <i
                  v-else
                  class="el-icon-plus avatar-uploader-icon"
                  :class="{ drop: detailsDisabled }"
                ></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="营业执照" prop="customerLicense">
              <el-upload
                :headers="headers"
                class="avatar-uploader"
                :action="$uploadUrl + upload"
                :show-file-list="false"
                :on-success="handleLicenseSuccess"
                :before-upload="beforeAvatarUpload"
                :accept="acceptString"
                :disabled="detailsDisabled"
              >
                <img
                  v-if="newCustomerModel.customerLicense"
                  :src="newCustomerModel.customerLicense"
                  class="avatar"
                />
                <i
                  v-else
                  class="el-icon-plus avatar-uploader-icon"
                  :class="{ drop: detailsDisabled }"
                ></i>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
      </template>
      <template #footer>
        <el-button type="primary" @click="dialogSave">确定</el-button>
        <el-button @click="$refs.ycDialog.dialogVisible = false"
        >取消
        </el-button>
      </template>
    </yc-dialog>

    <global-message
      v-if="isGlobalMessageShow"
      @receive="receive"
      :message="message"
    />
  </div>
</template>

<script>
  import {
    queryPageCustomer,
    insertCustomer,
    deleteCustomer,
    updateCustomer
  } from "@/api/clientOrObject/clientType"
  import { getToken } from "@/utils/auth"
  import { postUpload } from "@/api/upload"
  import ycDialog from "@/components/pageDialog"

  export default {
    data() {
      return {
        headers: {
          token: getToken()
        },
        tableData: [],
        count: 0,
        customerTypeOptions: [
          {
            label: "厂区类客户",
            value: "厂区类客户"
          },
          {
            label: "园区类客户",
            value: "园区类客户"
          },
          {
            label: "私人客户",
            value: "私人客户"
          },
          {
            label: "高能耗客户",
            value: "高能耗客户"
          },
          {
            label: "学校客户",
            value: "学校客户"
          }
        ],
        searchOptions: [
          {
            label: "顾清曦",
            value: "gqx"
          }
        ],
        searchForm: {
          searchInput: "",
          searchSelectValue: ""
        },

        detailsDisabled: false,
        isGlobalMessageShow: false,
        dialogCenterTitle: "",
        dialogTitle: "",
        message: "",
        pageIndex: 1,
        pageSize: 20,
        acceptString: ".png,  .jpg",
        fileType: ["image/png", "image/jpg"],
        upload: "/uploadManager/upload",
        loading: false,
        imgUrl: "",
        imgUrl1: "",
        newCustomerModel: {
          customerName: "",
          customerType: "",
          dockingPerson: "",
          customerPhone: "",
          customerUrl: "",
          customerLogo: "",
          customerLicense: "",
          id: "",
          remark1: "",
          dockingPhone: ""
        },
        rules: {
          customerName: [
            { required: true, message: "请输入客户名称", trigger: "blur" }
          ],
          dockingPhone: [
            { required: true, message: "请输入联系方式", trigger: "blur" }
          ],
          customerType: [
            { required: true, message: "请选择客户类型", trigger: "change" }
          ],
          dockingPerson: [
            { required: true, trigger: "blur", message: "请输入对接人员名称" }
          ],
          customerPhone: [
            { required: true, trigger: "blur", message: "请输入联系方式" }
          ],
          customerUrl: [
            { required: true, trigger: "blur", message: "请输入服务IP" }
          ],
          customerLogo: [
            { required: true, trigger: "blur", message: "请上传客户logo" }
          ],
          customerLicense: [
            { required: true, trigger: "blur", message: "请上传营业执照" }
          ]
        }
      }
    },
    components: {
      ycDialog
    },
    created() {
      this.getPageCustomer()
    },
    methods: {
      async getPageCustomer(pageIndex = 1, pageSize = 20, tableInfo = {}) {
        this.loading = true
        const { searchInput, searchSelectValue } = tableInfo
        const { object } = await queryPageCustomer({
          pageIndex,
          pageSize,
          customerName: searchInput,
          customerType: searchSelectValue
        })
        this.count = object.count
        this.tableData = object.data
        this.loading = false
      },
      newCustomer() {
        this.dialogCenterTitle = "客户基本信息"
        this.dialogTitle = "添加客户"
        this.$refs.ycDialog.dialogVisible = true
        this.$refs.loginFormRef?.clearValidate()
        this.detailsDisabled = false
        Object.keys(this.newCustomerModel).forEach((item) => {
          this.newCustomerModel[item] = ""
        })
      },
      handlerEdit(row) {
        this.$refs.ycDialog.dialogVisible = true
        this.$refs.loginFormRef?.clearValidate()
        this.detailsDisabled = false
        this.dialogCenterTitle = "客户基本信息"
        this.dialogTitle = "客户详情"
        this.newCustomerModel.customerName = row.customerName
        this.newCustomerModel.customerType = row.customerType
        this.newCustomerModel.dockingPerson = row.dockingPerson
        this.newCustomerModel.customerPhone = row.customerPhone
        this.newCustomerModel.customerUrl = row.customerUrl
        this.newCustomerModel.customerLogo = row.customerLogo
        this.newCustomerModel.remark1 = row.remark1
        this.newCustomerModel.id = row.id
        this.newCustomerModel.customerLicense = row.customerLicense
        this.newCustomerModel.dockingPhone = row.dockingPhone
      },

      searchClick() {
        this.getPageCustomer(1, 20, this.searchForm)
      },
      async dialogSave() {
        this.$refs.loginFormRef.validate(async (v) => {
          if (v) {
            if (this.detailsDisabled) {
              // 详情
              this.$refs.ycDialog.dialogVisible = false
            } else if (
              this.newCustomerModel.customerName &&
              this.newCustomerModel.id
            ) {
              // 编辑
              const { status } = await updateCustomer({
                ...this.newCustomerModel
              })
              if (status == 200) {
                this.isGlobalMessageShow = true
                this.message = "success"
                this.getPageCustomer()
                this.$refs.ycDialog.dialogVisible = false
              } else {
                this.message = "error"
              }
            } else {
              await this.newInsertCustomer()
              this.getPageCustomer()
              this.$refs.ycDialog.dialogVisible = false
            }
          }
        })
      },
      receive() {
        this.isGlobalMessageShow = false
      },
      async newInsertCustomer() {
        const { status } = await insertCustomer({ ...this.newCustomerModel })
        if (status == "200") {
          this.isGlobalMessageShow = true
          this.message = "success"
        } else {
          this.isGlobalMessageShow = true
          this.message = "error"
        }
      },
      async handlerDelete({ id }) {
        this.$confirm("确定删除此用户吗", "删除操作", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "error",
          center: true
        }).then(async () => {
          const { status } = await deleteCustomer({ id })
          if (status == 200) {
            console.log(id)
            this.getPageCustomer()
            this.isGlobalMessageShow = true
            this.message = "success"
          } else {
            this.message = "error"
          }
        })
      },
      async handlerProject(row) {
        this.$router.push({
          path: "/clientOrObject/object",
          query: { customerCode: row.customerCode }
        })
      },
      pagination(pageItem) {
        this.getPageCustomer(pageItem.page, pageItem.limit)
      },
      /**
       * 上传方法
       * */
      handleLogoSuccess1(id, file) {
        this.newCustomerModel.customerLogo = file.response.object.url
        this.imgUrl1 = file.response.object.url
      },
      handleLogoSuccess(id, file) {
        console.log(file, "file")
      },

      handleLicenseSuccess(id, file) {
        this.newCustomerModel.customerLicense = file.response.object.url
      },
      beforeAvatarUpload(file) {
        // const isType = this.fileType.includes(file.type)
        const isLt2M = file.size / 1024 / 1024 < 5

        // if (!isJPG) {
        //   this.$message.error("上传头像图片只能是 JPG 格式!")
        // }
        // if (!isType) {
        //   this.$message.error("上传文件格式有问题！")
        // }
        // if (!isLt2M) {
        //   this.$message.error("上传头像图片大小不能超过 5MB!")
        // }
        // return isJPG && isLt2M
        // return isType && isLt2M
      },
      refresh() {
        Object.keys(this.searchForm).forEach((item) => {
          this.searchForm[item] = ""
        })
        this.getPageCustomer()
      }
    }
  }
</script>
<style lang="scss" scoped>
  .clientType {
    .title-container {
      display: flex;
      justify-content: flex-end;

      .left-box {
        width: 550px;

        .formClass {
          display: flex;
          justify-content: space-around;
          margin-right: 8px;

          .el-form-item {
            margin-top: 20px;
            margin-bottom: 0;

            .el-input {
              width: 216px;
            }

            .el-select {
              width: 171px;
              margin-left: 10px;
            }
          }
        }
      }
    }
  }
</style>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
    /* cursor: no-drop; */
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .drop {
    cursor: no-drop;
  }
</style>
